<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        let str = " hello world! "
        function solution(str) {
            function removeExtraSpaceStr(arr) {
                let slowIndex = 0
                let fastIndex = 0
                let len = arr.length
                while (fastIndex < len) {
                    if ((arr[fastIndex] === ' ') && (fastIndex === 0 || arr[fastIndex - 1] === ' ')) {
                        fastIndex++
                    } else {
                        arr[slowIndex++] = arr[fastIndex++]
                    }
                }
                arr.length = arr[slowIndex - 1] === ' ' ? slowIndex - 1 : slowIndex
            }

            function reverseArr(arr, start, end) {
                while (start < end) {
                    [arr[start], arr[end]] = [arr[end], arr[start]]
                    start++
                    end--
                }
            }
            const arr = Array.from(str)
            removeExtraSpaceStr(arr)
            reverseArr(arr, 0, arr.length - 1)

            let start = 0
            for (let i = 0; i < arr.length; i++) {
                if (arr[i] === ' ' || i === arr.length) {
                    reverseArr(arr, start, i - 1)
                    start = i + 1
                }
            }
            return arr.join('')
        }


        const res = solution(str)
        console.log(res)
    </script>
</body>

</html>